<?php

namespace app\common\model;

use app\common\model\Common;
use app\common\model\SystemRole;
use think\model\concern\SoftDelete;

class SystemMenu extends Common
{
    use SoftDelete;
    protected $deleteTime = 'del_time';
    protected $table = 'system_menu';
    // 查询左侧菜单栏
    public function getMenu($pid = 0,$status=1){

        $field = 'id,title,icon,href,target,pid';
        $sort = 'sort '.$this->sysconfig['sort'];
        $where = [];
        $where[] = ['pid','=',$pid];
        $where[] = ['type','=',1];
        if($status == 1){
            $where[] = ['status','=',1];
        }
        $admin = cache('admin_user'.session('admin_user'));
        if($admin['is_supper'] != 1){
            $role = SystemRole::find($admin['role_id']);
            $where[] = ['id','in',$role['power']];
        }
        $menu = $this->getAllOrder($where,$field,$sort)->toArray();
        // 判断是否有子集
        foreach($menu as &$v){
            $wherechild = ['pid'=>$pid,'type'=>1];
            if($status == 1){
                $wherechild['status'] = 1;
            }
            $v['icon'] = 'fa '.$v['icon'];
            $has = $this->countRows($wherechild);
            if($has){
                $v['child'] = $this->getMenu($v['id']);
            }
        }
        return $menu;
    }
    // 删除菜单
    public function destroyMenu($id){
        SystemMenu::destroy($id);
        $haschild = $this->countRows(['pid'=>$id]);
        if($haschild){
            $menu = $this->getAll(['pid'=>$id],'id,pid');
            foreach($menu as $v){
                $this->destroyMenu($v['id']);
            }
        }
    }
    // 查询权限
    public function getRole($pid=0,$arr=[]){
        $field = 'id,title,icon,href,target,pid';
        $sort = 'sort '.$this->sysconfig['sort'];
        $where = ['pid'=>$pid,'type'=>1,'status'=>1];
        $menu = $this->getAllOrder($where,$field,$sort)->toArray();
        // 判断是否有子集
        foreach($menu as &$v){
            $v['spread'] = true;
            // 判断是否含有
            if(in_array($v['id'],$arr)){
                $v['checked'] = true;
            }else{
                $v['checked'] = false;
            }
            $wherechild = ['pid'=>$pid,'type'=>1,'status'=>1];
            $has = $this->countRows($wherechild);
            if($has){
                $v['children'] = $this->getRole($v['id'],$arr);
            }
        }
        return $menu;
    }
}
